package crons

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"hotgo/internal/dao"
	"hotgo/internal/library/cron"
	"hotgo/internal/service"
)

func init() {
	cron.Register(CheckOcr)
}

// CheckOcr OCR完成检测
var CheckOcr = &cCheckOcr{name: "check_ocr"}

type cCheckOcr struct {
	name string
}

func (c *cCheckOcr) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cCheckOcr) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	g.Log().Info(ctx, "[xldebug][定时检查]:CRON: check_ocr start")
	ocrs, count, err := dao.RecordActivity.Ctx(ctx).Where(dao.RecordActivity.Columns().RecordEnd, "1").Where(dao.RecordActivity.Columns().OcrEnd, "1").Where(dao.RecordActivity.Columns().MergeEnd, "0").AllAndCount(false)
	if nil != err {
		g.Log().Errorf(ctx, "[xldebug][定时检查]:cron check ocr err:%v", err)
		return err
	}
	g.Log().Info(ctx, "CRON: count", count)
	if 0 == count {
		return nil
	}
	for _, ocr := range ocrs {
		if ocrNums, ok := ocr["ocr_nums"]; !ok {
			continue
		} else {
			frameCounts := ocrNums.Uint64()
			aid := ocr["activity_id"].Int()
			ocrFrameCounts, err := g.Redis().HGet(ctx, "ocrhandlenum", fmt.Sprintf("activity_%d", aid))
			if nil != err {
				g.Log().Errorf(ctx, "[xldebug][定时检查]:CRON get redis frame counts error:%v", err)
				continue
			}
			g.Log().Info(ctx, "[xldebug][定时检查]:CRON", frameCounts, ":", ocrFrameCounts.Uint64())
			if frameCounts > 0 && frameCounts == ocrFrameCounts.Uint64() {
				err = service.Recorder().FlagMergeStart(ctx, aid)
				if nil != err {
					g.Log().Errorf(ctx, "[xldebug][定时检查]:更新活动: %d 合并个人视频状态为进行中时出现sql错误:%v", aid, err)
					continue
				}

				// --  @# 开始进行活动内个人视频合并
				go service.Recorder().Merge(ctx, aid)

			}
			continue
		}

	}
	return nil
}
